package user_service

import (
	"encoding/json"
	"fmt"
	"net/http"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/utils/tools"

	"github.com/gin-gonic/gin"
)

type BdService struct{}

// 查询北大的教师端数据
func (bd *BdService) FetchInfo(ctx *gin.Context) (string, error) {
	client := &http.Client{}
	request, err := http.NewRequest("POST", variable.Config.Beida.Url, nil)
	request.Header.Add("token", variable.Config.Beida.Token)
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		return "", err
	}
	resp, err := client.Do(request)
	if err != nil {
		return "", err
	}
	if resp != nil {
		defer resp.Body.Close()
	}

	res := make(map[string]interface{})
	err = tools.ReadResponseBodyCtx(ctx, resp, &res)
	if err != nil {
		return "", err
	}

	b, _ := json.Marshal(res["data"])
	return string(b), nil
}

// 北大的教师数据
func (bd *BdService) OptionTeacherData(ctx *gin.Context) error {
	var schoolName = "北京大学"
	// 1. 获取北大数据
	s, err := bd.FetchInfo(ctx)
	if err != nil {
		return err
	}
	// 2. 转换数据
	var teacherInfoList []model.TeacherInfo
	err = json.Unmarshal([]byte(s), &teacherInfoList)
	if err != nil {
		return err
	}
	// 3. 根据loginName查询教师是否存在
	var loginNameList []string

	for i := 0; i < len(teacherInfoList); i++ {
		loginNameList = append(loginNameList, teacherInfoList[i].LoginName)
	}
	var userList []tables.User
	d := variable.DB.MySQL.Where("school = ? and account_name in (?)", schoolName, loginNameList).Find(&userList)
	if d.Error != nil {
		return d.Error
	}
	// 4. 数据准备
	var mapUserList = make(map[string]tables.User, len(userList))
	for i := 0; i < len(userList); i++ {
		mapUserList[*userList[i].AccountName] = userList[i]
	}
	// a) 查询学校 和学院的
	c, _ := new(tables.Constitute).GetInfoByWhere(map[string]interface{}{"type": "school", "name": schoolName})
	if c.ID == 0 {
		return fmt.Errorf(schoolName + "不存在")
	}
	schoolId := c.ID
	agentId := c.AgentID

	cfgInfoList, _ := new(tables.Constitute).GetConstituteByBelongToId(int(schoolId))
	if len(cfgInfoList) == 0 {
		return fmt.Errorf(schoolName + "的学院信息不存在")
	}
	// b) ConstituteID map
	var constituteMap = make(map[string]uint, len(cfgInfoList))
	for _, v := range cfgInfoList {
		constituteMap[v.Name] = v.Id
	}
	// 兼容学校信息
	constituteMap[schoolName] = schoolId

	// 5. 插入数据
	for _, v := range teacherInfoList {
		flag := false
		if v.College == "就业中心" { // 学校管理员
			flag = true
		}
		if _, ok := mapUserList[v.LoginName]; ok {
			continue
		}

		// 组装数据插入
		var u = tables.User{
			Name:         v.LoginName,
			AccountName:  &v.LoginName,
			Type:         tables.UserTypeAdmin,
			School:       schoolName,
			ConstituteID: schoolId,
			AgentID:      *agentId,
			Level:        tables.RolesLevel2,
			Academy:      v.College,
			CreateUserId: 0,
			RoleId:       3, // 默认学校管理员
			IsSync:       true,
		}
		if !flag {
			u.RoleId = 4                 // 学院管理员
			u.Level = tables.RolesLevel3 // 学院管理员
			u.ConstituteID = constituteMap[u.Academy]
		}

		// 保存到数据库中
		tables.AddUser(u)
	}
	return nil
}
